package com.tongguan.paypos.fragment;

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tongguan.paypos.R;
import com.tongguan.paypos.adapter.TransBillsAdapter;
import com.tongguan.paypos.base.BaseFragment;
import com.tongguan.paypos.base.MyApplication;
import com.tongguan.paypos.common.AppConstants;
import com.tongguan.paypos.common.RequestCallback;
import com.tongguan.paypos.common.UrlConstants;
import com.tongguan.paypos.common.User;
import com.tongguan.paypos.entity.BillsInfo;
import com.tongguan.paypos.entity.PayType;
import com.tongguan.paypos.entity.PayTypeInfo;
import com.tongguan.paypos.entity.TransBillsInfo;
import com.tongguan.paypos.utils.DateUtils;
import com.tongguan.paypos.utils.L;
import com.tongguan.paypos.utils.NumberUtils;
import com.tongguan.paypos.utils.ToastUtils;
import com.tongguan.paypos.view.PullUpLoadListView;
import com.tongguan.paypos.view.calendar.TimePopWind;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Joylive on 2016/12/18 .
 */

public class TransBillsFragment extends BaseFragment {

    @BindView(R.id.tv_price_total)
    TextView mTvPriceTotal;
    @BindView(R.id.bills_time_layout)
    LinearLayout mBillsTime;
    @BindView(R.id.tv_all)
    TextView mTvAll;
    @BindView(R.id.tv_success)
    TextView mTvSuccess;
    @BindView(R.id.tv_revoke)
    TextView mTvRevoke;
    @BindView(R.id.tv_reversal)
    TextView mTvReversal;
    @BindView(R.id.pull_up_add_list_view_bills)
    PullUpLoadListView mListView;

    private String startTime;
    private String endTime;
    private int page = 1;
    private int size = 15;
    private int total = 1;//总页数
    private String type; //默认 "" 查全部的流水
    private ArrayList<BillsInfo> mDatas = new ArrayList<>();
    private TransBillsAdapter mAdapter;
    private boolean shouldLoadMore = true;//加载更多数据
    private ArrayList<PayType> mPayTypes = new ArrayList<>();
    private String[] items;
    private boolean isFirstLoad = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_bills_total, container, false);
        setTitle("账单");
        ButterKnife.bind(this, rootView);
        mAdapter = new TransBillsAdapter(frmCtx, mDatas);
        mListView.setAdapter(mAdapter);
        startTime = DateUtils.getBeforeDate(-7);
        endTime = DateUtils.getDate_();
        loadData(type);
        loadPayType();
        initEvent();
        return rootView;
    }

    private void loadPayType() {
        if (MyApplication.getInstance().getPayTypes() == null) {
            params = new HashMap<>();
            params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
            RequestCallback.post(frmCtx, UrlConstants.GET_PAY_TYPE, params, new AbstractRequestCallback() {
                @Override
                public void onResponse(String response, int id) {
                    PayTypeInfo payTypeInfo = PayTypeInfo.objectFromData(response);
                    if (payTypeInfo.getStatus() != 100) {
                        ToastUtils.showCustom(frmCtx, payTypeInfo.getMessage());
                        return;
                    }
                    List<PayTypeInfo.PayTypesBean> payTypes = payTypeInfo.getPayTypes();
                    if (payTypes == null || payTypes.size() == 0) {
                        ToastUtils.showCustom(frmCtx, "无支付方式");
                        return;
                    }
                    //固定支付方式
                    for (PayTypeInfo.PayTypesBean payType : payTypes) {
                        PayType data = AppConstants.payTypeMap.get(payType.getType());
                        if (data == null){
                            continue;
                        }
                        mPayTypes.add(data);
                    }

                    if (mPayTypes.size() == 0) {
                        L.d("支付方式不在本地中");
                        return;
                    }if (MyApplication.getInstance().getPayTypes() == null) {
                        MyApplication.getInstance().setPayTypes(mPayTypes);
                    }
                    int length = mPayTypes.size();
                    items = new String[length + 1];
                    for (int i = 0; i < length; i++) {
                        items[i] = mPayTypes.get(i).getName();
                    }
                    items[length] = "总交易查询";
                }
            });
        } else {
            L.d("application中已经存在");
            mPayTypes = MyApplication.getInstance().getPayTypes();
            int length = mPayTypes.size();
            items = new String[length + 1];
            for (int i = 0; i < length; i++) {
                items[i] = mPayTypes.get(i).getName();
            }
            items[length] = "总交易查询";
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.category, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_category:
                if (items == null || items.length == 0) {
                    ToastUtils.showCustom(frmCtx, "没有支付方式，请重新加载");
                    return false;
                }
                new AlertDialog.Builder(frmCtx).setTitle("选择查询方式")
                        .setItems(items, (dialog, which) -> {
                            dialog.dismiss();
                            //重新加载
                            page = 1;
                            mDatas.clear();
                            mAdapter.notifyDataSetChanged();
                            shouldLoadMore = true;
                            isFirstLoad = true;
                            String cont = items[which];
                            if ("总交易查询".equals(cont)) {
                                type = null;
                                loadData(type);
                            } else {
                                for (PayType payType : mPayTypes) {
                                    if (payType.getName().equals(cont)) {
                                        type = payType.getType();
                                        loadData(type);
                                    }
                                }
                            }
                        }).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void initEvent() {
        mListView.setOnPullUpLoadListener(() -> {
            if (isFirstLoad) {
                //首次加载不触发
                return;
            }
            if (page <= total) {
                loadData(type);
            } else {
                mListView.onPullUpLoadFinished(true);
            }
        });

        mListView.setOnItemClickListener((parent, view, position, id) -> {
            if (position == mDatas.size()) {
                return;
            }
            String type = mDatas.get(position).getChannelId();
            if ("YL".equals(type) || "DK".equals(type) || "XL".equals(type)) {
                TransBillsBelowDetailFragment fragment = new TransBillsBelowDetailFragment();
                Bundle bundle = new Bundle();
                bundle.putParcelable(TransBillsBelowDetailFragment.EXCHANGE_RESULT, mDatas.get(position));
                fragment.setArguments(bundle);
                getFragmentManager().beginTransaction().hide(this).add(R.id.container, fragment).addToBackStack(null).commit();
            } else {
                TransBillsOnlineDetailFragment fragment = new TransBillsOnlineDetailFragment();
                Bundle bundle = new Bundle();
                bundle.putParcelable(TransBillsOnlineDetailFragment.ORDER_DATA, mDatas.get(position));
                fragment.setArguments(bundle);
                getFragmentManager().beginTransaction().hide(this).add(R.id.container, fragment).addToBackStack(null).commit();
            }
        });

        mBillsTime.setOnClickListener(v -> new TimePopWind(frmCtx).showPopWindows(v));

        TimePopWind.setmTimeCallBack((startTime1, endTime1) -> {
            startTime = startTime1 + " 00:00:00";
            endTime = endTime1 + " 59:59:59";
            //重新加载
            page = 1;
            mDatas.clear();
            mAdapter.notifyDataSetChanged();
            shouldLoadMore = true;
            isFirstLoad = true;
            loadData(type);
        });
    }

    private void loadData(String type) {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_CASHIER, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_BILLS_PAGE, page);
        params.put(UrlConstants.KEY_BILLS_COUNT, size);
        params.put(UrlConstants.KEY_BILLS_START_TIME, startTime);
        params.put(UrlConstants.KEY_BILLS_END_TIME, endTime);
        params.put(UrlConstants.KEY_CHANNEL_ID, type);
        RequestCallback.post(frmCtx, UrlConstants.TRANS_BILLS, params, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {
                TransBillsInfo transBillsInfo = TransBillsInfo.objectFromData(response);
                if (transBillsInfo.getStatus() != 100) {
                    ToastUtils.showCustom(frmCtx, transBillsInfo.getMessage());
                    return;
                }
                setView(transBillsInfo);
                if (shouldLoadMore) {
                    shouldLoadMore = false;
                    if (transBillsInfo.getTotal() % size == 0) {
                        total = transBillsInfo.getTotal() / size;
                    } else {
                        total = transBillsInfo.getTotal() / size + 1;
                    }
                    L.d("页数 ：" + total);
                }
                List<BillsInfo> orders = transBillsInfo.getOrders();
                page++;
                mListView.onPullUpLoadFinished(false);
                mDatas.addAll(orders);
                mAdapter.notifyDataSetChanged();
                if (isFirstLoad) {
                    isFirstLoad = false;
                }
            }
        });
    }

    private void setView(TransBillsInfo transBillsInfo) {
        String moneyType = NumberUtils.getMoneyType(Double.valueOf(transBillsInfo.getOrderPayMoneys()));
        mTvPriceTotal.setText(moneyType);
        mTvAll.setText(String.valueOf(transBillsInfo.getTotal()));
        mTvSuccess.setText(String.valueOf(transBillsInfo.getPaySuccess()));
        mTvRevoke.setText(String.valueOf(transBillsInfo.getPayRefund()));
        mTvReversal.setText(String.valueOf(transBillsInfo.getPayCorrection()));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RequestCallback.cancelAllRequest();
    }
}
